package great.easychat.help.util;

import android.app.Activity;

import great.easychat.help.bean.ConfigBean;
import great.easychat.help.dialog.CommonDialog;
import great.easychat.help.dialog.UpdateDialog;
import great.easychat.help.update.IupdateDialogCallBack;
import great.easychat.help.update.UpdateDownloader;

public class UpdateHelper {

    public static boolean startCheck(Activity context) {
        ConfigBean configBean = UserInfoManger.config;
        if (configBean == null) {
            return false;
        }
        int lastVer =  configBean.getVersion();
        int currVer = Integer.valueOf(Util.getAppVersionCode(context));
        if (lastVer > currVer) {
            up(context);
            return true;
        } else {
            return false;
        }
    }

    private static void up(Activity context) {
        // 是否强制更新 0false 1true
        ConfigBean configBean = UserInfoManger.config;
        if (configBean == null) {
            return;
        }
        int isForce = configBean.getIs_force_update();
        if (isForce == 1) {
            toDown(context, configBean);
        } else {
            CommonDialog commonDialog = new CommonDialog();
            commonDialog.setContent(configBean.getVersion_content());
            commonDialog.show(context, new CommonDialog.Callback() {
                @Override
                public void sure() {
                    toDown(context, configBean);
                }

                @Override
                public void cancel() {

                }
            });
        }

    }

    private static void toDown(Activity context, ConfigBean configBean) {
        UpdateDialog updateDialog = new UpdateDialog();
        updateDialog.show(context);
        new UpdateDownloader(context).attachDialogCallBack(configBean.getVersion() + "", configBean.getDownUrl()
                , "great.easychat.help.fileProvider", new IupdateDialogCallBack() {
                    @Override
                    public void onUpdateProgress(Long current, Long total) {
                        int p = (int) (current * 100 / total);
                        DebugLog.d("onUpdateProgress-->" + current + " --- " + total + " --- " + p + "%");
                        updateDialog.setProgress(p);
                    }

                    @Override
                    public void onComplete(Boolean isFinish) {
                        updateDialog.cancelDialog();
                        DebugLog.d("onUpdateProgress--> onComplete " + isFinish);
                    }
                }
        );
    }


}
